<template>
  <view class="charity-detail-page">
    <!-- 活动封面图改为轮播图 -->
    <swiper class="cover-swiper" :indicator-dots="true" :autoplay="true" interval="3000" duration="500" circular="true">
      <swiper-item v-for="(image, index) in activity.images || defaultImages" :key="index">
        <view class="swiper-item" :style="{ backgroundColor: activity.bgColor || 'rgba(118, 179, 255, 0.8)' }">
          <image v-if="image.url" :src="image.url" mode="aspectFill" class="swiper-image"></image>
          <text v-else class="image-text">{{ image.text || '活动图片' }}</text>
        </view>
      </swiper-item>
    </swiper>
    
    <!-- 活动状态 -->
    <view class="status-badge" :class="{ 'active': activity.status === '进行中', 'coming': activity.status === '即将开始', 'ended': activity.status === '已结束' }">
      <text>{{ activity.status || '进行中' }}</text>
    </view>
    
    <!-- 活动基本信息 -->
    <view class="activity-info">
      <view class="activity-title">{{ activity.name || '加载中...' }}</view>
      
      <view class="info-row">
        <view class="info-icon">🏢</view>
        <view class="info-content">
          <text class="info-label">主办方</text>
          <text class="info-value">{{ activity.organizer || '加载中...' }}</text>
        </view>
      </view>
      
      <view class="info-row">
        <view class="info-icon">🕒</view>
        <view class="info-content">
          <text class="info-label">活动时间</text>
          <text class="info-value">{{ activity.time || '加载中...' }}</text>
        </view>
      </view>
      
      <view class="info-row">
        <view class="info-icon">📍</view>
        <view class="info-content">
          <text class="info-label">活动地点</text>
          <text class="info-value">{{ activity.location || '加载中...' }}</text>
        </view>
      </view>
      
      <view class="info-row" v-if="activity.quota">
        <view class="info-icon">👥</view>
        <view class="info-content">
          <text class="info-label">活动名额</text>
          <text class="info-value">{{ activity.quota || '不限' }} {{ activity.quota ? '人' : '' }}</text>
        </view>
      </view>
    </view>
    
    <!-- 活动详情 -->
    <view class="activity-detail">
      <view class="section-title">
        <view class="title-bar"></view>
        <text>活动详情</text>
      </view>
      
      <view class="detail-content">
        <view class="detail-section">
          <view class="section-subtitle">活动背景</view>
          <text class="detail-text">{{ activity.background || detailContent.background }}</text>
        </view>
        
        <view class="detail-section">
          <view class="section-subtitle">活动内容</view>
          <text class="detail-text">{{ activity.content || detailContent.content }}</text>
        </view>
        
        <view class="detail-section">
          <view class="section-subtitle">参与方式</view>
          <text class="detail-text">{{ activity.howToJoin || detailContent.howToJoin }}</text>
        </view>
        
        <view class="detail-section" v-if="activity.notes || detailContent.notes">
          <view class="section-subtitle">注意事项</view>
          <text class="detail-text">{{ activity.notes || detailContent.notes }}</text>
        </view>
      </view>
    </view>
    
    <!-- 已报名人员 -->
    <view class="participants-section" v-if="activity.participants">
      <view class="section-title">
        <view class="title-bar"></view>
        <text>已报名 ({{ activity.participants }}人)</text>
      </view>
      
      <view class="participants-preview">
        <view class="avatar-list">
          <view class="avatar-item" v-for="n in Math.min(activity.participants, 8)" :key="n">
            <text>头像</text>
          </view>
          <view class="more-avatar" v-if="activity.participants > 8">
            <text>+{{ activity.participants - 8 }}</text>
          </view>
        </view>
        
        <view class="participants-info">
          <text class="latest-join">最近报名：张先生、王女士...</text>
        </view>
      </view>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="action-bar">
      <view class="primary-btn" :class="{ 'disabled': activity.status === '已结束' || isRegistered }" @tap="registerActivity">
        <text>{{ getButtonText() }}</text>
      </view>
    </view>
    
    <!-- 成功提示弹窗 -->
    <view class="success-popup" v-if="showSuccessPopup">
      <view class="popup-content">
        <view class="success-icon">✅</view>
        <view class="success-title">报名成功</view>
        <view class="success-message">您已成功报名该活动</view>
        <view class="popup-btn" @tap="closePopup">确定</view>
      </view>
    </view>
    
    <!-- 入住人选择弹窗 -->
    <view class="resident-popup" v-if="showResidentPopup">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">选择参与活动的入住人</text>
          <text class="close-icon" @tap="closeResidentPopup">✕</text>
        </view>
        
        <view class="residents-list">
          <view class="empty-tip" v-if="residents.length === 0">
            <text>暂无入住人信息，请先添加入住人</text>
            <view class="add-resident-btn" @tap="goToAddResident">
              <text>添加入住人</text>
            </view>
          </view>
          
          <template v-else>
            <view class="resident-item" v-for="resident in residents" :key="resident.id" @tap="toggleSelectResident(resident)">
              <view class="resident-info">
                <view class="resident-avatar">
                  <image v-if="resident.avatar" :src="resident.avatar" mode="aspectFill" class="avatar-image"></image>
                  <text v-else>{{ resident.name.substr(0, 1) }}</text>
                </view>
                <view class="resident-detail">
                  <text class="resident-name">{{ resident.name }}</text>
                  <text class="resident-id-card">{{ maskIdCard(resident.idCard) }}</text>
                </view>
              </view>
              <view v-if="registeredResidentIds.includes(resident.id)" class="resident-status">
                <text class="status-text">已报名</text>
              </view>
              <view v-else class="resident-checkbox" :class="{ 'checked': selectedResidents.includes(resident.id) }">
                <text v-if="selectedResidents.includes(resident.id)" class="check-icon">✓</text>
              </view>
            </view>
            
            <!-- 添加新入住人按钮 -->
            <view class="resident-item add-new-resident" @tap="showAddNewResident">
              <view class="resident-info">
                <view class="resident-avatar add-icon">
                  <text>+</text>
                </view>
                <view class="resident-detail">
                  <text class="resident-name">添加新入住人</text>
                  <text class="resident-id-card">快速添加并报名</text>
                </view>
              </view>
            </view>
          </template>
        </view>
        
        <view class="popup-footer">
          <view class="footer-tips">
            <text>已选 {{ selectedResidents.length }} 人</text>
          </view>
          <view class="popup-btn confirm-btn" :class="{ 'disabled': selectedResidents.length === 0 }" @tap="confirmRegistration">
            <text>确认报名</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 新增入住人弹窗 -->
    <view class="new-resident-popup" v-if="showNewResidentPopup">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">新增入住人</text>
          <text class="close-icon" @tap="closeNewResidentPopup">✕</text>
        </view>
        
        <view class="form-content">
          <view class="avatar-upload">
            <view class="avatar-preview" @tap="chooseAvatar">
              <image v-if="newResident.avatar" :src="newResident.avatar" mode="aspectFill" class="preview-image"></image>
              <view v-else class="avatar-placeholder">
                <text class="placeholder-icon">+</text>
                <text class="placeholder-text">上传头像</text>
              </view>
            </view>
          </view>
          
          <view class="form-item">
            <text class="form-label">姓名</text>
            <input class="form-input" type="text" v-model="newResident.name" placeholder="请输入姓名" />
          </view>
          
          <view class="form-item">
            <text class="form-label">身份证号</text>
            <input class="form-input" type="idcard" v-model="newResident.idCard" placeholder="请输入身份证号" />
          </view>
          
          <view class="form-item">
            <text class="form-label">出生日期</text>
            <picker class="form-picker" mode="date" :value="newResident.birthDate" @change="handleBirthDateChange">
              <view class="picker-value">{{ newResident.birthDate || '请选择出生日期' }}</view>
            </picker>
          </view>
          
          <view class="form-item">
            <text class="form-label">性别</text>
            <radio-group class="form-radio-group" @change="handleGenderChange">
              <label class="radio-item">
                <radio value="男" :checked="newResident.gender === '男'" color="#2c7873" />
                <text class="radio-text">男</text>
              </label>
              <label class="radio-item">
                <radio value="女" :checked="newResident.gender === '女'" color="#2c7873" />
                <text class="radio-text">女</text>
              </label>
            </radio-group>
          </view>
          
          <view class="form-item">
            <text class="form-label">联系电话</text>
            <input class="form-input" type="number" v-model="newResident.phone" placeholder="请输入联系电话" />
          </view>
          
          <view class="form-item">
            <text class="form-label">账号与本人关系</text>
            <picker class="form-picker" :range="relationOptions" @change="handleRelationChange">
              <view class="picker-value">{{ newResident.relation || '账号与本人关系' }}</view>
            </picker>
          </view>
        </view>
        
        <view class="popup-footer">
          <view class="popup-btn cancel-btn" @tap="closeNewResidentPopup">
            <text>取消</text>
          </view>
          <view class="popup-btn confirm-btn" @tap="addNewResident">
            <text>添加并选择</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';

// 活动数据
const activity = ref({});
const activityId = ref(null);
const isRegistered = ref(false);
const showSuccessPopup = ref(false);
const showResidentPopup = ref(false);

// 入住人数据
const residents = ref([]);
const selectedResidents = ref([]);

// 默认轮播图数据
const defaultImages = [
  { text: '活动图片1', bgColor: 'rgba(118, 179, 255, 0.8)' },
  { text: '活动图片2', bgColor: 'rgba(128, 203, 196, 0.8)' },
  { text: '活动图片3', bgColor: 'rgba(255, 107, 107, 0.8)' }
];

// 模拟详情内容
const detailContent = {
  background: "随着社会老龄化的加剧，越来越多的老年人需要社会的关爱和支持。本次活动旨在通过志愿服务，为老年人提供陪伴和关爱，让他们感受社会的温暖。",
  content: "1. 志愿者与老人一对一结对陪伴交流\n2. 为老人提供日常生活帮助\n3. 开展趣味文化活动和健康知识普及\n4. 帮助老人学习使用智能设备\n5. 举办小型联欢活动，共同度过愉快时光",
  howToJoin: "1. 点击页面底部立即报名按钮\n2. 填写个人信息并提交\n3. 等待组织方确认并分配服务对象\n4. 按时参加活动",
  notes: "1. 参与者需要准时到达活动地点\n2. 请保持耐心和友善，尊重老人的生活习惯\n3. 活动期间请保持良好的卫生习惯\n4. 如有特殊情况无法参加，请提前联系组织方"
};

// 检查是否已报名
const checkRegistrationStatus = (id) => {
  try {
    const registeredActivities = uni.getStorageSync('registeredActivities') || [];
    isRegistered.value = registeredActivities.includes(Number(id));
  } catch(e) {
    console.error('获取报名状态失败', e);
    isRegistered.value = false;
  }
};

// 保存报名状态到本地
const saveRegistrationStatus = (id) => {
  try {
    let registeredActivities = uni.getStorageSync('registeredActivities') || [];
    // 确保ID不重复
    if (!registeredActivities.includes(Number(id))) {
      registeredActivities.push(Number(id));
      uni.setStorageSync('registeredActivities', registeredActivities);
    }
  } catch(e) {
    console.error('保存报名状态失败', e);
  }
};

// 检查入住人是否已报名
const checkResidentRegistrationStatus = (id) => {
  try {
    const registeredResidentsMap = uni.getStorageSync('registeredResidentsMap') || {};
    const activityRegistrations = registeredResidentsMap[Number(id)] || [];
    
    // 返回已报名的入住人ID列表
    return activityRegistrations;
  } catch(e) {
    console.error('获取入住人报名状态失败', e);
    return [];
  }
};

// 保存入住人报名状态到本地
const saveResidentRegistrationStatus = (activityId, residentIds) => {
  try {
    // 获取已有的报名记录
    let registeredResidentsMap = uni.getStorageSync('registeredResidentsMap') || {};
    // 获取当前活动的报名入住人
    const activityRegistrations = registeredResidentsMap[Number(activityId)] || [];
    
    // 添加新的入住人ID，不重复添加
    const updatedRegistrations = [...new Set([...activityRegistrations, ...residentIds])];
    
    // 更新存储
    registeredResidentsMap[Number(activityId)] = updatedRegistrations;
    uni.setStorageSync('registeredResidentsMap', registeredResidentsMap);
    
    console.log('保存入住人报名状态成功:', registeredResidentsMap);
  } catch(e) {
    console.error('保存入住人报名状态失败', e);
  }
};

// 新增入住人相关变量
const showNewResidentPopup = ref(false);
const newResident = ref({
  name: '',
  idCard: '',
  phone: '',
  relation: '',
  relationCode: '',
  avatar: '',
  birthDate: '',
  gender: ''
});
const relationOptions = ['本人', '父亲', '母亲', '配偶', '其他'];

// 关系代码映射
const relationCodeMap = {
  '本人': 1,
  '父亲': 2,
  '母亲': 3,
  '配偶': 4,
  '其他': 5
};

// 处理关系选择器变化
const handleRelationChange = (e) => {
  const selectedRelation = relationOptions[e.detail.value];
  const relationCode = relationCodeMap[selectedRelation];
  const relationText = selectedRelation;
  
  // 保存关系文本和代码
  newResident.value.relation = relationText;
  newResident.value.relationCode = relationCode;
  
  console.log('选择的关系代码:', relationCode, '关系文本:', relationText);
};

// 显示新增入住人弹窗
const showAddNewResident = () => {
  // 重置表单数据
  newResident.value = {
    name: '',
    idCard: '',
    phone: '',
    relation: '',
    relationCode: '',
    avatar: '',
    birthDate: '',
    gender: ''
  };
  showNewResidentPopup.value = true;
};

// 关闭新增入住人弹窗
const closeNewResidentPopup = () => {
  showNewResidentPopup.value = false;
};

// 验证身份证号
const validateIdCard = (idCard) => {
  // 简单验证，实际应用中可以使用更复杂的验证规则
  const pattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  return pattern.test(idCard);
};

// 添加新入住人
const addNewResident = () => {
  // 表单验证
  if (!newResident.value.name) {
    uni.showToast({
      title: '请输入姓名',
      icon: 'none'
    });
    return;
  }
  
  if (!newResident.value.idCard || !validateIdCard(newResident.value.idCard)) {
    uni.showToast({
      title: '请输入有效的身份证号',
      icon: 'none'
    });
    return;
  }
  
  if (!newResident.value.phone || newResident.value.phone.length !== 11) {
    uni.showToast({
      title: '请输入有效的手机号',
      icon: 'none'
    });
    return;
  }
  
  if (!newResident.value.relation) {
    uni.showToast({
      title: '请选择与本人关系',
      icon: 'none'
    });
    return;
  }
  
  // 生成新ID (实际应用中应该由后端生成)
  const newId = residents.value.length > 0 ? Math.max(...residents.value.map(r => r.id)) + 1 : 1;
  
  // 创建新入住人对象
  const resident = {
    id: newId,
    name: newResident.value.name,
    idCard: newResident.value.idCard,
    phone: newResident.value.phone,
    relation: newResident.value.relation,
    relationCode: newResident.value.relationCode,
    avatar: newResident.value.avatar || '',
    birthDate: newResident.value.birthDate,
    gender: newResident.value.gender
  };
  
  // 添加到入住人列表
  residents.value.push(resident);
  
  // 保存到本地存储 (实际应用中应该提交到后端)
  try {
    let storedResidents = uni.getStorageSync('residents') || [];
    storedResidents.push(resident);
    uni.setStorageSync('residents', storedResidents);
    
    uni.showToast({
      title: '入住人添加成功',
      icon: 'success'
    });
    
    // 自动选中新添加的入住人
    selectedResidents.value.push(newId);
    
    // 关闭新增弹窗
    closeNewResidentPopup();
  } catch(e) {
    console.error('保存入住人信息失败', e);
    uni.showToast({
      title: '保存失败，请重试',
      icon: 'none'
    });
  }
};

// 修改入住人数据获取方法
const fetchResidents = () => {
  // 从本地存储获取入住人数据
  try {
    const storedResidents = uni.getStorageSync('residents');
    if (storedResidents && storedResidents.length > 0) {
      residents.value = storedResidents;
    } else {
      // 没有存储数据，使用默认数据
      residents.value = [
        { id: 1, name: '张大爷', idCard: '110101195006153256', phone: '13800138000', relation: '本人', relationCode: 1 },
        { id: 2, name: '李奶奶', idCard: '110101194503126542', phone: '13900139000', relation: '配偶', relationCode: 4 },
        { id: 3, name: '王叔叔', idCard: '110101196204125436', phone: '13700137000', relation: '亲属', relationCode: 5 }
      ];
      // 保存默认数据到本地存储
      uni.setStorageSync('residents', residents.value);
    }
  } catch(e) {
    console.error('获取入住人数据失败', e);
    // 使用默认数据
    residents.value = [
      { id: 1, name: '张大爷', idCard: '110101195006153256', phone: '13800138000', relation: '本人', relationCode: 1 },
      { id: 2, name: '李奶奶', idCard: '110101194503126542', phone: '13900139000', relation: '配偶', relationCode: 4 },
      { id: 3, name: '王叔叔', idCard: '110101196204125436', phone: '13700137000', relation: '亲属', relationCode: 5 }
    ];
  }
};

// 选择/取消选择入住人
const toggleSelectResident = (resident) => {
  // 检查该入住人是否已报名
  if (registeredResidentIds.value.includes(resident.id)) {
    uni.showToast({
      title: '该入住人已报名此活动',
      icon: 'none'
    });
    return;
  }
  
  const index = selectedResidents.value.indexOf(resident.id);
  if (index === -1) {
    // 新增选择
    selectedResidents.value.push(resident.id);
  } else {
    // 取消选择
    selectedResidents.value.splice(index, 1);
  }
};

// 格式化身份证号（中间部分用*隐藏）
const maskIdCard = (idCard) => {
  if (!idCard || idCard.length < 15) return idCard;
  return idCard.substr(0, 6) + '********' + idCard.substr(14);
};

// 打开入住人选择弹窗
const openResidentPopup = () => {
  fetchResidents();
  selectedResidents.value = [];
  
  // 获取已报名的入住人列表
  registeredResidentIds.value = checkResidentRegistrationStatus(activityId.value);
  console.log('该活动已报名的入住人:', registeredResidentIds.value);
  
  showResidentPopup.value = true;
};

// 关闭入住人选择弹窗
const closeResidentPopup = () => {
  showResidentPopup.value = false;
};

// 跳转到添加入住人页面
const goToAddResident = () => {
  closeResidentPopup();
  // 跳转到添加入住人页面
  uni.navigateTo({
    url: '/pages/profile/add-resident'
  });
};

// 确认报名
const confirmRegistration = () => {
  if (selectedResidents.value.length === 0) {
    uni.showToast({
      title: '请选择参与活动的入住人',
      icon: 'none'
    });
    return;
  }
  
  // 模拟向后端发送报名请求
  console.log('提交报名信息:', {
    activityId: activity.value.id,
    residentIds: selectedResidents.value
  });
  
  // 保存入住人报名状态
  saveResidentRegistrationStatus(activity.value.id, selectedResidents.value);
  
  // 关闭入住人选择弹窗
  closeResidentPopup();
  
  // 显示成功提示
  showSuccessPopup.value = true;
  
  // 更新参与人数
  activity.value.participants += selectedResidents.value.length;
};

// 获取按钮文本
const getButtonText = () => {
  if (activity.value.status === '已结束') {
    return '活动已结束';
  }
  
  return '立即报名';
};

// 获取活动详情
const getActivityDetail = (id) => {
  // 模拟接口请求
  setTimeout(() => {
    // 模拟数据
    const charityActivities = [
      {
        id: 401,
        name: '夕阳红健康知识讲座',
        organizer: '阳光社区服务中心',
        time: '2023-06-10 14:00-16:00',
        location: '海淀区社区文化中心',
        status: '进行中',
        participants: 42,
        images: [
          { text: '健康讲座图片1' },
          { text: '健康讲座图片2' },
          { text: '健康讲座图片3' }
        ],
        bgColor: 'rgba(118, 179, 255, 0.2)',
        category: 'health',
        quota: 50
      },
      {
        id: 402,
        name: '老年人手机使用培训',
        organizer: '科技助老协会',
        time: '2023-06-15 09:30-11:30',
        location: '朝阳区老年活动中心',
        status: '即将开始',
        participants: 28,
        images: [
          { text: '手机培训图片1' },
          { text: '手机培训图片2' },
          { text: '手机培训图片3' }
        ],
        bgColor: 'rgba(128, 203, 196, 0.2)',
        category: 'culture'
      },
      {
        id: 403,
        name: '重阳节关爱老人志愿服务',
        organizer: '爱心志愿者协会',
        time: '2023-10-23 09:00-17:00',
        location: '全市各养老院',
        status: '即将开始',
        participants: 156,
        images: [
          { text: '重阳节活动图片1' },
          { text: '重阳节活动图片2' },
          { text: '重阳节活动图片3' }
        ],
        bgColor: 'rgba(255, 107, 107, 0.2)',
        category: 'volunteer',
        quota: 200
      },
      {
        id: 404,
        name: '老年人才艺展示活动',
        organizer: '市文化局',
        time: '2023-05-20 13:00-17:00',
        location: '市民文化广场',
        status: '已结束',
        participants: 78,
        images: [
          { text: '才艺展示图片1' },
          { text: '才艺展示图片2' },
          { text: '才艺展示图片3' }
        ],
        bgColor: 'rgba(255, 193, 7, 0.2)',
        category: 'culture'
      }
    ];
    
    // 查找对应ID的活动
    const found = charityActivities.find(item => item.id === Number(id));
    
    if (found) {
      activity.value = found;
    } else {
      // 没找到，使用默认数据
      activity.value = {
        id: Number(id) || 999,
        name: '公益活动详情',
        organizer: '养老服务中心',
        time: '2023-06-01 09:00-11:00',
        location: '社区服务中心',
        status: '进行中',
        participants: 35,
        images: defaultImages,
        bgColor: 'rgba(118, 179, 255, 0.8)',
        category: 'volunteer',
        quota: 50
      };
    }
    
    console.log('获取到活动详情:', activity.value);
  }, 500);
};

// 报名活动
const registerActivity = () => {
  if (activity.value.status === '已结束') {
    uni.showToast({
      title: '活动已结束，无法报名',
      icon: 'none'
    });
    return;
  }
  
  // 打开入住人选择弹窗
  openResidentPopup();
};

// 关闭弹窗
const closePopup = () => {
  showSuccessPopup.value = false;
};

// 查看活动详情
const viewActivityDetail = (id) => {
  console.log('查看活动详情:', id);
  uni.navigateTo({
    url: `/pages/charity-detail/index?id=${id}`
  });
};

// 取消报名
const cancelRegistration = (id, residentId) => {
  console.log('取消报名:', id, residentId);
  uni.showModal({
    title: '取消报名',
    content: '确定要取消该入住人的报名吗？',
    success: (res) => {
      if (res.confirm) {
        try {
          // 从本地存储中删除该入住人的活动报名记录
          let registeredResidentsMap = uni.getStorageSync('registeredResidentsMap') || {};
          const activityRegistrations = registeredResidentsMap[Number(id)] || [];
          
          // 如果提供了入住人ID，只移除特定入住人
          if (residentId) {
            const index = activityRegistrations.indexOf(Number(residentId));
            if (index > -1) {
              activityRegistrations.splice(index, 1);
              registeredResidentsMap[Number(id)] = activityRegistrations;
              uni.setStorageSync('registeredResidentsMap', registeredResidentsMap);
              
              // 更新入住人列表状态
              registeredResidentIds.value = activityRegistrations;
              
              uni.showToast({
                title: '已取消报名',
                icon: 'success'
              });
              
              // 减少参与人数
              if (activity.value.participants > 0) {
                activity.value.participants -= 1;
              }
            }
          } else {
            // 如果没提供入住人ID，清空该活动所有报名
            delete registeredResidentsMap[Number(id)];
            uni.setStorageSync('registeredResidentsMap', registeredResidentsMap);
            
            registeredResidentIds.value = [];
            
            uni.showToast({
              title: '已取消所有报名',
              icon: 'success'
            });
          }
          
          // 如果在列表页面，可以刷新列表
          const pages = getCurrentPages();
          const prevPage = pages[pages.length - 2];
          if (prevPage && prevPage.route.includes('profile/charity-registrations')) {
            // 返回上一页并刷新
            setTimeout(() => {
              uni.navigateBack({
                success: () => {
                  // 通知上一页刷新数据
                  if (prevPage.$vm && prevPage.$vm.refreshRegistrations) {
                    prevPage.$vm.refreshRegistrations();
                  }
                }
              });
            }, 500);
          }
        } catch(e) {
          console.error('取消报名失败', e);
          uni.showToast({
            title: '操作失败，请重试',
            icon: 'none'
          });
        }
      }
    }
  });
};

// 添加已报名入住人列表的响应式变量
const registeredResidentIds = ref([]);

// 添加选择头像的方法
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      newResident.value.avatar = res.tempFilePaths[0];
    },
    fail: (err) => {
      console.error('选择头像失败', err);
      uni.showToast({
        title: '选择头像失败，请重试',
        icon: 'none'
      });
    }
  });
};

// 处理出生日期变化
const handleBirthDateChange = (e) => {
  newResident.value.birthDate = e.detail.value;
};

// 处理性别变化
const handleGenderChange = (e) => {
  newResident.value.gender = e.detail.value;
};

// 页面加载
onMounted(() => {
  // 获取路由参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  
  if (currentPage && currentPage.options) {
    activityId.value = currentPage.options.id;
    getActivityDetail(activityId.value);
  } else {
    // 如果没有参数，加载默认数据
    activityId.value = 999; // 设置默认ID
    getActivityDetail(null);
  }
});
</script>

<style lang="scss">
page {
  background-color: #f5f5f5;
}

.charity-detail-page {
  min-height: 100vh;
  padding-bottom: 30px; // 减小底部填充，因为按钮现在是浮动的
  position: relative;
  
  // 轮播图
  .cover-swiper {
    width: 100%;
    height: 250px;
    
    .swiper-item {
      width: 100%;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .swiper-image {
      width: 100%;
      height: 100%;
    }
    
    .image-text {
      color: white;
      font-size: 18px;
    }
  }
  
  .status-badge {
    position: absolute;
    top: 15px;
    right: 15px;
    padding: 5px 12px;
    border-radius: 20px;
    background-color: #8d8d8d;
    z-index: 9;
    
    text {
      font-size: 12px;
      color: #fff;
      font-weight: 600;
    }
    
    &.active {
      background-color: #4CAF50;
    }
    
    &.coming {
      background-color: #2196F3;
    }
    
    &.ended {
      background-color: #9E9E9E;
    }
  }
  
  // 活动基本信息
  .activity-info {
    padding: 20px 15px;
    margin-top: -20px;
    background-color: #fff;
    border-radius: 20px 20px 0 0;
    position: relative;
    z-index: 10;
    box-shadow: 0 -4px 10px rgba(0, 0, 0, 0.05);
    
    .activity-title {
      font-size: 18px;
      font-weight: 600;
      color: #2c7873;
      margin-bottom: 15px;
    }
    
    .info-row {
      display: flex;
      margin-bottom: 12px;
      
      .info-icon {
        width: 24px;
        margin-right: 10px;
        font-size: 16px;
      }
      
      .info-content {
        flex: 1;
        
        .info-label {
          font-size: 14px;
          color: #6FB3B8;
          margin-right: 8px;
        }
        
        .info-value {
          font-size: 14px;
          color: #2c7873;
        }
      }
    }
  }
  
  // 活动详情
  .activity-detail {
    margin: 10px 0;
    padding: 20px 15px;
    background-color: #fff;
    
    .section-title {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      
      .title-bar {
        width: 4px;
        height: 18px;
        background-color: #2c7873;
        margin-right: 8px;
      }
      
      text {
        font-size: 16px;
        font-weight: 600;
        color: #2c7873;
      }
    }
    
    .detail-content {
      .detail-section {
        margin-bottom: 15px;
        
        .section-subtitle {
          font-size: 15px;
          font-weight: 600;
          color: #2c7873;
          margin-bottom: 10px;
        }
        
        .detail-text {
          font-size: 14px;
          color: #6FB3B8;
          line-height: 1.6;
        }
      }
    }
  }
  
  // 已报名人员
  .participants-section {
    margin: 10px 0;
    padding: 20px 15px;
    background-color: #fff;
    
    .participants-preview {
      padding: 10px 0;
      
      .avatar-list {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 10px;
        
        .avatar-item, .more-avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          background-color: rgba(111, 179, 184, 0.2);
          margin-right: 8px;
          margin-bottom: 8px;
          display: flex;
          justify-content: center;
          align-items: center;
          font-size: 12px;
          color: #6FB3B8;
          border: 1px solid rgba(111, 179, 184, 0.4);
        }
        
        .more-avatar {
          background-color: rgba(111, 179, 184, 0.1);
        }
      }
      
      .participants-info {
        font-size: 13px;
        color: #6FB3B8;
      }
    }
  }
  
  // 底部操作栏
  .action-bar {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: auto;
    padding: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: transparent;
    box-shadow: none;
    z-index: 90;
    
    .primary-btn {
      height: 50px;
      width: 120px;
      background: linear-gradient(to right, #2c7873, #6FB3B8);
      border-radius: 25px;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 0;
      box-shadow: 0 4px 12px rgba(44, 120, 115, 0.3);
      
      text {
        color: #fff;
        font-size: 15px;
        font-weight: 600;
      }
      
      &.disabled {
        background: #cccccc;
        opacity: 0.8;
      }
      
      &:active {
        transform: scale(0.95);
      }
    }
  }
  
  // 成功弹窗
  .success-popup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 999;
    
    .popup-content {
      width: 80%;
      padding: 30px 20px;
      background-color: #fff;
      border-radius: 12px;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .success-icon {
        font-size: 40px;
        margin-bottom: 15px;
      }
      
      .success-title {
        font-size: 18px;
        font-weight: 600;
        color: #2c7873;
        margin-bottom: 10px;
      }
      
      .success-message {
        font-size: 14px;
        color: #6FB3B8;
        margin-bottom: 20px;
      }
      
      .popup-btn {
        width: 60%;
        height: 46px;
        background-color: #2c7873;
        border-radius: 23px;
        display: flex;
        justify-content: center;
        align-items: center;
        
        text {
          color: #fff;
          font-size: 16px;
          font-weight: 600;
        }
        
        &:active {
          opacity: 0.9;
        }
      }
    }
  }
  
  // 入住人选择弹窗
  .resident-popup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 999;
    
    .popup-content {
      width: 90%;
      height: 70%;
      background-color: #fff;
      border-radius: 12px;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      
      .popup-header {
        padding: 15px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #f0f0f0;
        
        .popup-title {
          font-size: 16px;
          font-weight: 600;
          color: #2c7873;
        }
        
        .close-icon {
          font-size: 18px;
          color: #999;
          padding: 5px;
        }
      }
      
      .residents-list {
        flex: 1;
        overflow-y: auto;
        padding: 15px;
        
        .empty-tip {
          padding: 40px 20px;
          text-align: center;
          
          text {
            font-size: 14px;
            color: #999;
            display: block;
            margin-bottom: 20px;
          }
          
          .add-resident-btn {
            width: 60%;
            height: 42px;
            background: linear-gradient(to right, #2c7873, #6FB3B8);
            border-radius: 21px;
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0 auto;
            
            text {
              color: #fff;
              font-size: 14px;
              font-weight: 500;
              margin: 0;
            }
            
            &:active {
              opacity: 0.9;
            }
          }
        }
        
        .resident-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 15px 0;
          border-bottom: 1px solid #f5f5f5;
          
          &:last-child {
            border-bottom: none;
          }
          
          &:active {
            background-color: rgba(111, 179, 184, 0.05);
          }
          
          &.add-new-resident {
            margin-top: 10px;
            background-color: rgba(111, 179, 184, 0.05);
            border-radius: 8px;
            
            .resident-avatar {
              background-color: rgba(44, 120, 115, 0.1);
              
              &.add-icon {
                background-color: rgba(44, 120, 115, 0.6);
                
                text {
                  color: #fff;
                  font-size: 22px;
                  line-height: 22px;
                  font-weight: 600;
                }
              }
            }
            
            .resident-name {
              color: #2c7873 !important;
              font-weight: 600 !important;
            }
            
            .resident-id-card {
              color: #6FB3B8 !important;
            }
          }
          
          .resident-info {
            display: flex;
            align-items: center;
            
            .resident-avatar {
              width: 44px;
              height: 44px;
              border-radius: 50%;
              background-color: rgba(44, 120, 115, 0.1);
              display: flex;
              justify-content: center;
              align-items: center;
              margin-right: 12px;
              
              .avatar-image {
                width: 100%;
                height: 100%;
                border-radius: 50%;
                object-fit: cover;
              }
            }
            
            .resident-detail {
              .resident-name {
                font-size: 15px;
                color: #333;
                font-weight: 500;
                margin-bottom: 4px;
                display: block;
              }
              
              .resident-id-card {
                font-size: 13px;
                color: #999;
                display: block;
              }
            }
          }
          
          .resident-status {
            padding: 0 10px;
            background-color: rgba(44, 120, 115, 0.1);
            border-radius: 10px;
            
            .status-text {
              font-size: 12px;
              color: #2c7873;
              font-weight: 500;
            }
          }
          
          .resident-checkbox {
            width: 22px;
            height: 22px;
            border-radius: 50%;
            border: 1px solid #ddd;
            display: flex;
            justify-content: center;
            align-items: center;
            
            &.checked {
              background-color: #2c7873;
              border-color: #2c7873;
            }
            
            .check-icon {
              color: #fff;
              font-size: 14px;
              font-weight: bold;
            }
          }
        }
      }
      
      .popup-footer {
        padding: 15px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-top: 1px solid #f0f0f0;
        
        .footer-tips {
          font-size: 14px;
          color: #666;
        }
        
        .confirm-btn {
          width: 140px;
          height: 42px;
          background: linear-gradient(to right, #2c7873, #6FB3B8);
          border-radius: 21px;
          display: flex;
          justify-content: center;
          align-items: center;
          
          text {
            color: #fff;
            font-size: 15px;
            font-weight: 600;
          }
          
          &.disabled {
            background: #cccccc;
            opacity: 0.8;
          }
          
          &:active {
            transform: scale(0.98);
          }
        }
      }
    }
  }
  
  // 新增入住人弹窗
  .new-resident-popup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 999;
    
    .popup-content {
      width: 85%;
      max-height: 600px;
      background-color: #fff;
      border-radius: 16px;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
      
      .popup-header {
        padding: 18px 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #f0f0f0;
        background-color: #f9f9f9;
        
        .popup-title {
          font-size: 17px;
          font-weight: 600;
          color: #2c7873;
        }
        
        .close-icon {
          font-size: 20px;
          color: #999;
          padding: 5px;
          line-height: 20px;
        }
      }
      
      .form-content {
        flex: 1;
        padding: 20px;
        overflow-y: auto;
        
        .avatar-upload {
          display: flex;
          justify-content: center;
          margin-bottom: 25px;
          
          .avatar-preview {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            background-color: #f5f5f5;
            border: 1px dashed #6FB3B8;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            overflow: hidden;
            position: relative;
            
            .preview-image {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }
            
            .avatar-placeholder {
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
              
              .placeholder-icon {
                font-size: 24px;
                color: #6FB3B8;
                margin-bottom: 6px;
              }
              
              .placeholder-text {
                font-size: 12px;
                color: #6FB3B8;
              }
            }
            
            &:active {
              opacity: 0.8;
            }
          }
        }
        
        .form-item {
          margin-bottom: 20px;
          
          .form-label {
            font-size: 14px;
            color: #6FB3B8;
            margin-bottom: 8px;
            display: block;
            font-weight: 500;
          }
          
          .form-input {
            height: 48px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 0 15px;
            background-color: #f9f9f9;
            font-size: 15px;
            color: #333;
            width: 100%;
            box-sizing: border-box;
          }
          
          .form-picker {
            width: 100%;
            height: 40px;
            padding: 0 15px;
            background-color: #f8f8f8;
            border-radius: 6px;
            display: flex;
            align-items: center;
            
            .picker-value {
              width: 100%;
              font-size: 14px;
              color: #333;
              
              &:empty::before {
                content: '请选择';
                color: #999;
              }
            }
          }
          
          .form-radio-group {
            display: flex;
            align-items: center;
            
            .radio-item {
              display: flex;
              align-items: center;
              margin-right: 20px;
              
              .radio-text {
                font-size: 14px;
                color: #333;
                margin-left: 4px;
              }
            }
          }
        }
      }
      
      .popup-footer {
        padding: 15px 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-top: 1px solid #f0f0f0;
        background-color: #f9f9f9;
        
        .popup-btn {
          flex: 1;
          height: 46px;
          border-radius: 23px;
          display: flex;
          justify-content: center;
          align-items: center;
          margin: 0 8px;
          
          &.cancel-btn {
            background-color: #f0f0f0;
            
            text {
              color: #666;
            }
          }
          
          &.confirm-btn {
            background: linear-gradient(to right, #2c7873, #6FB3B8);
            
            text {
              color: #fff;
            }
          }
          
          text {
            font-size: 15px;
            font-weight: 600;
          }
          
          &:active {
            transform: scale(0.98);
          }
        }
      }
    }
  }
}
</style> 